package com.dmai.capacity.platform.oauth.common.service.impl;

import com.dmai.capacity.platform.common.dto.GatewayLogGroupResult;
import com.dmai.capacity.platform.common.model.OauthUserBillMonth;
import com.dmai.capacity.platform.common.utils.DateUtils;
import com.dmai.capacity.platform.common.utils.IdGenerator;
import com.dmai.capacity.platform.oauth.common.mapper.GatewayLogDao;
import com.dmai.capacity.platform.oauth.common.mapper.OauthUserBillMonthDao;
import com.dmai.capacity.platform.oauth.common.service.ICapabilityVolumeChargeRuleService;
import com.dmai.capacity.platform.oauth.common.service.IOauthUserBillService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;


@Service
public class OauthUserBillServiceImpl implements IOauthUserBillService {

    @Autowired
    private OauthUserBillMonthDao billDao;

    @Autowired
    private GatewayLogDao logDao;

    @Autowired
    private ICapabilityVolumeChargeRuleService volumeChargeRuleService;


    @Override
    public int reCalculate() {
        List<GatewayLogGroupResult> groupResults = logDao.groupByUserCapability(DateUtils.getFirstDayOfMonth() + " 00:00:00", DateUtils.getLastDayOfMonth() + " 23:59:59");
        if (CollectionUtils.isEmpty(groupResults)) {
            return 0;
        }

        int _result = 0;
        for (GatewayLogGroupResult item : groupResults) {
            OauthUserBillMonth bill = billDao.find(item.getUserid(), item.getClientId(), item.getCapabilityId(), LocalDate.now().getYear(), LocalDate.now().getMonthValue());
            if (bill == null) {
                bill = new OauthUserBillMonth();
                bill.setId(IdGenerator.getId());
                bill.setUserid(item.getUserid());
                bill.setClientId(item.getClientId());
                bill.setCapabilityId(item.getCapabilityId());
                bill.setYear(LocalDate.now().getYear());
                bill.setMonth(LocalDate.now().getMonthValue());
                bill.setVolumeChargeCount(item.getCount());
                bill.setAmount(volumeChargeRuleService.getAmount(item.getCapabilityId(), item.getCount()));

                _result += billDao.save(bill);
            } else {
                bill.setVolumeChargeCount(item.getCount());
                bill.setAmount(volumeChargeRuleService.getAmount(item.getCapabilityId(), item.getCount()));

                _result += billDao.update(bill);
            }
        }

        return _result;
    }
}
